package com.kfm.base.thread.day01;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicInteger;

public class Exer02 {

    public static void main(String[] args) {
        final AtomicInteger num = new AtomicInteger();

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                while (!Thread.interrupted()){
//                    num.getAndIncrement(); // i ++
//                    num.incrementAndGet(); // ++ i
                    num.getAndIncrement();
                }
            }
        };

        Thread t1 = new Thread(runnable);

        t1.start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        t1.interrupt();

        System.out.println(num.get());


    }

    public static void demo1(){
        Callable<Long> callable = new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                long sum = 0;
                while (!Thread.interrupted()){
                    sum += 1;
                }
                return sum;
            }
        };

        FutureTask<Long> futureTask = new FutureTask<>(callable);

        Thread t1 = new Thread(futureTask);

        t1.start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        t1.interrupt(); // 中断线程

        try {
            System.out.println(futureTask.get());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}
